<?php

require_once(dirname(__FILE__).'/../lib/curl.php');

class TanTanXanga {
    
    var $loggedin = false;
    var $error = array();
    var $response;
    var $headers;
    var $cookies;
    var $user;
    var $options;
    
    function TanTanXanga() {
        $this->req =& new TanTanCurl();
        $this->options = array();
    }
    
    function getError() {
        return $this->error;
    }
    function setError($err) {
        $this->error = $err;
    }
    function setOptions($opts, $value=false) {
        if ($value) {
            $this->options[$opts] = $value;
        } else {
            $this->options = $opts;
        }
        if ($this->options['comments'] == 'off') $this->options['comments'] = false;
    }
    function getOption($key) {
        return $this->options[$key];
    }
    function isLoggedIn() {
        return $this->loggedin ? true : false;
    }

    function login($user, $passwd) {
        if ($this->isLoggedIn()) {
            $this->logout();
        }
        
        /*
            do login action
        */
        
        // get login key
        $loginpage = 'http://www.xanga.com/signin.aspx';
        $this->req->setURL($loginpage);
        $this->req->setMethod(HTTP_REQUEST_METHOD_GET);
        //$this->req->addPostData('var', 'key');
        
        $this->req->sendRequest();
        $this->headers = $this->req->getResponseHeader();
        $this->cookies = $this->req->getResponseCookies();
        $this->response = $this->req->getResponseBody();
        
        $__VIEWSTATE = $this->_getViewState($this->req->getResponseBody());
        if (!$__VIEWSTATE) {
            $this->setError('Unable to contact Xanga');
            return false;
        }
        $this->req->setMethod(HTTP_REQUEST_METHOD_POST);
        
        $this->req->addPostData('__VIEWSTATE', $__VIEWSTATE);
        $this->req->addPostData('txtSigninUsername', $user);
        $this->req->addPostData('txtSigninPassword', $passwd);
        $this->req->addPostData('btnSignin', 'Sign In');
        $this->req->addPostData('txtRegisterEmail', '');
        $this->req->addPostData('txtRegisterUsername', '');
        $this->req->addPostData('txtRegisterPassword1', '');
        $this->req->addPostData('txtRegisterPassword2', '');
        
        foreach ($this->cookies as $c) {
            $this->req->addCookie($c['name'], $c['value']);
        }
        
        $this->req->sendRequest();
        $this->headers = $this->req->getResponseHeader();
        $this->cookies = $this->req->getResponseCookies();
        $this->response = $this->req->getResponseBody();

        $this->req->clearPostData();
               
        /*
            CHECK IF LOGIN WAS OK
        */
        $ok = isset($this->cookies['u']) && isset($this->cookies['x']) && isset($this->cookies['y']);
        
        if (!$ok) {
            $this->setError('Invalid username or password.');
            return false;
        } else {
            foreach ($this->cookies as $c) {
                $this->req->addCookie($c['name'], $c['value']);
            }
            
            $this->user = $user;
            $this->loggedin = true;
            return true;
        }
    }    
    function logout() {
        $this->loggedin = false;
        $this->user = false;
    }
    function getSession() {
        return $this->cookies;
    }
    function setSession($session, $user) {
        if (!is_array($session)) {
            return false;
        }
        $this->user = $user;
        $this->cookies = $session;
        foreach ($this->cookies as $c) {
            $this->req->addCookie($c['name'], $c['value']);
        }
        $this->loggedin = true;
        return true;
    }
    
    function deletePost($xanga_id) {
        $this->_updatePost('delete', $xanga_id, array());
    }
    
    function createPost($post) {
        $this->_updatePost('add', false, $post);
        return $this->getLastestPostID();

    }
    
    function editPost($xanga_id, $post) {
        $this->_updatePost('edit', $xanga_id, $post);
    }
    
    function _updatePost($action, $xanga_id, $post) {
        if ($this->getOption('premium')) {
            $this->req->setURL("http://premium.xanga.com/private/xtools/xtoolspremium.aspx?plain=1".  ($xanga_id ? '&uid='.$xanga_id : ''));
        } else {
            $this->req->setURL("http://www.xanga.com/private/xtools/xtoolsclassic.aspx" . ($xanga_id ? '?uid='.$xanga_id : ''));
        }
        // 

    	$this->req->sendRequest();
    	$__VIEWSTATE = $this->_getViewState($this->req->getResponseBody());
    	
        $this->req->addPostData('__EVENTTARGET', '');
        $this->req->addPostData('__EVENTARGUMENT', '');
        $this->req->addPostData('__VIEWSTATE', $__VIEWSTATE); // may need to get a key here
        $this->req->addPostData('xztitle1', '');
        $this->req->addPostData('xztitle2', '');
        $this->req->addPostData('xzasin1', '');
        $this->req->addPostData('chkComments', $this->getOption('comments')); // enable comments?
        $this->req->addPostData('radAccess', '1'); // public access
        $this->req->addPostData('xbgcolor', '');
        $this->req->addPostData('xbordercolor', '');
        $this->req->addPostData('xcontent', '');
        $this->req->addPostData('xcopypost', '');
        
        if ($action == 'delete') {
            $this->req->addPostData('btnSubmit', 'Delete');
            $this->req->addPostData('txtPlainText', 'This post has been deleted.');
        } else {
            $this->req->addPostData('btnSubmit', 'Submit');
            //$this->req->addPostData('txtTitle', $post['title']);
            $this->req->addPostData('txtPlainText', $post['body']);
        }
        
        $this->req->setMethod(HTTP_REQUEST_METHOD_POST);
        $this->req->sendRequest(); // do the post
        $response = $this->req->getResponseBody();
    }
    
    function getLastestPostID() {
        $this->req->setURL("http://www.xanga.com/rss.aspx?user=".$this->user);
        $this->req->sendRequest();
        //if (ereg('.*/([0-9]*)/item\.html.*', $this->req->getResponseBody(), $out)) {
        if (preg_match('/\/([0-9]*)\/item\.html/', $this->req->getResponseBody(), $matches)) {
            return $matches[1];
        } else {
            return false;
        }
    }
    
    function _getViewState($body) {
        if (ereg('__VIEWSTATE" value="([^"]*)"', $body, $out)) {
    		return $out[1];
    	} else {
    	    return '';
    	}
    }
}

?>